import React, { useState, useEffect } from 'react';

import {
    Accordion,
    Modal,
    List,
    Button,
    Radio,
    Toast,
    TextareaItem,
} from 'antd-mobile';
import { withRouter } from 'react-router-dom'
import AMap from 'AMap';
import mark from "@/assets/svg/mark.svg"
import { trial, trialFail, trialSuccess, PostAddApply, PostCancelApply, PostRefund } from "@/api/tutor/orderList.js"
import { payProtocolHtml } from "@/api/tutor/tutor.js"

import { GetListResumeFroSelect as GetListResume } from "@/api/tutor/biographicalNotes.js"
import { R, ORDER_STATUSES, createInfoWindow } from "@/assets/js/dict";

const prompt = Modal.prompt;

//待定订单申请
function PreOrderDetails (props) {
    console.log("PreAppl----->", props);

    // 订单详情
    let [orderDetailsObject, setOrderDetailsObject] = useState({
        students: [],
        learn_hours: '[]'
    });



    function doFlush () {
        props.doFlush();
    }


    let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));

    // 简历列表
    let [resumeSelectionObj, setResumeSelectionObj] = useState({
        resumeSelectionVisible: false,
        resumeOptionList: [],
        resumeSelection: '',
    })

    // 申请退款
    let [refundDetailsVisible, setRefundDetailsVisible] = useState(false);


    let [protocol, setProtocol] = useState("");

    let [showProtocol, setShowProtocol] = useState(false);

    function showRefound () {
        setRefundDetailsVisible(true);
    }

    function hideRefund () {
        setRefundDetailsVisible(false);
    }

    // 退款说明
    let [comment, setComment] = useState('')


    //进行试讲
    let [trialVisible, setTrialVisible] = useState(false),
        [address, setAddress] = useState("");

    function showTrial () {
        setTrialVisible(true);
    }

    function hideTrial () {
        setTrialVisible(false);
    }

    //试讲成功
    let [successComment, setSuccessComment] = useState('');
    let [trialSuccessVisible, setTrialSuccessVisible] = useState(false);

    function showTrialSuccess () {
        setTrialSuccessVisible(true);
    }

    function hideTrialSuccess () {
        setTrialSuccessVisible(false)
    }

    //试讲失败
    let [failComment, setFailComment] = useState('');
    let [trialFailVisible, setTrialFailVisible] = useState(false);

    function showTrialFail () {
        setTrialFailVisible(true);
    }

    function hideTrialFail () {
        setTrialFailVisible(false)

    }


    // 选中报名
    let handleSubmit = () => {
        console.log('resumeSelection -------->>>', resumeSelectionObj.resumeSelection)
        let postData = {
            tutor_id: userInfo.id,
            resume_id: resumeSelectionObj.resumeSelection,
            order_id: orderDetailsObject.id
        };

        PostAddApply(postData).then(res => {
            if (res.code == '000000') {
                Toast.success('订单报名成功', 3, function () {
                    props.history.goBack()
                })
            }
        }).catch(err => {

        })
    }

    // 家教取消报名
    let handleCancelApply = (note) => {
        console.log('resumeSelection -------->>>', orderDetailsObject)
        let postData = {
            tutor_id: userInfo.id,
            order_id: orderDetailsObject.id,
            note: note
        };
        if (!!note) {
            PostCancelApply(postData).then(res => {
                if (res.code == '000000') {
                    Toast.success('取消报名成功', 3, function () {
                        props.history.push({
                            pathname:"/mainTutor",
                            query:{
                                selectedTab: "lookFor"
                            }
                        })
                    })
                }
            }).catch(err => {
                console.error(err);
            })
        } else {
            Toast.offline("请填写取消报名的原因", 2);
        }

    };

    //试讲开始
    function handleTrialStart () {
        if (!!address) {
            trial({ apply_id: orderDetailsObject.apply_id, address: address }, (res) => {
                if (R.isSuccess(res)) {
                    Toast.success("更新成功", 2, ()=> {
                        doFlush();
                        hideTrial();
                    });
                }
            })

        } else {
            Toast.fail("请您填写试讲地址", 2);
        }
    }

    //试讲成功
    function handleTrialSuccess () {
        if (!!successComment) {
            trialSuccess({ apply_id: orderDetailsObject.apply_id, comment: successComment }, (res) => {
                if (R.isSuccess(res)) {
                    Toast.success("操作成功", 3, () => props.history.push("/workingOrdersOfTutor"), false);
                }
                hideTrialSuccess();
            })
        } else {
            Toast.fail("请您填试讲成功说明", 2);
        }
    }


    //试讲失败
    function handleTrialFail () {
        if (!!failComment) {
            trialFail({ apply_id: orderDetailsObject.apply_id, comment: failComment }, (res) => {
                if (R.isSuccess(res)) {
                    Toast.success("操作成功", 3, () =>  props.history.push("/historyOrdersOfTutor"), false);
                }
                hideTrialFail();
            });
        } else {
            Toast.fail("请您填试讲失败的说明", 2);
        }
    }

    // 确定退款
    let handleRefund = () => {
        let postData = {
            tutor_id: userInfo.id,
            order_id: orderDetailsObject.id,
            comment: comment,
        };

        PostRefund(postData).then(res => {
            if (res.code == '000000') {
                Toast.success('退款申请成功', 3, function () {
                    setRefundDetailsVisible(false);
                    props.history.push("/historyOrdersOfTutor");
                })
            }
        }).catch(err => {
            console.error(err);
        })
    };

    function showP () {
        setShowProtocol(true);
    }

    function hideP () {
        setShowProtocol(false);
    }

    function btnFn () {
        const status = orderDetailsObject.status;
        return (
            <div className="form-footer">
                <Button type="primary"
                    style={{ display: (status === ORDER_STATUSES.SELECTED) ? 'block' : 'none' }}
                    onClick={showP}
                >去支付</Button>
                <Button type="warning"
                    style={{ display: (orderDetailsObject.isApplied && (status === ORDER_STATUSES.PUBLISH || status === ORDER_STATUSES.FULL || status === ORDER_STATUSES.SELECTED)) ? 'block' : 'none' }}
                    onClick={() => {
                        prompt(
                            '订单取消说明',
                            '',
                            [
                                { text: '取消' },
                                { text: '提交', onPress: note => handleCancelApply(note) },
                            ],
                            'default',
                        )
                    }}
                >取消报名</Button>
                {/*<Button type="primary"
                    style={{ display: (status === ORDER_STATUSES.NO_DEAL || status === ORDER_STATUSES.PAYED || status === ORDER_STATUSES.UNSATISFACTORY) ? 'block' : 'none' }}
                    onClick={showRefound}
                >申请退款</Button>*/}

                <Button type="primary"
                    style={{ display: (status === ORDER_STATUSES.PAYED) ? 'block' : 'none' }}
                    onClick={showTrial}
                >进行试讲</Button>

                <Button type="primary"
                    style={{ display: (status === ORDER_STATUSES.TRIAL) ? 'block' : 'none' }}
                    onClick={showTrialSuccess}
                >试讲成功</Button>

                <Button type="warning"
                    style={{ display: (status === ORDER_STATUSES.TRIAL) ? 'block' : 'none' }}
                    onClick={showTrialFail}
                >试讲失败</Button>
            </div>);
    }

    useEffect(() => {
        let obj = props.orderDetailsObject;
        setOrderDetailsObject(obj);
        payProtocolHtml(res => {
            if (res.code === "000000") {
                setProtocol(res.responseData)
            }
        });

        //加载地图
        if (null !== obj.longitude && null !== obj.latitude) {
            let pp = [obj.longitude, obj.latitude];
            let mapInstance = new AMap.Map('amap', {
                resizeEnable: true,
                zoomEnable: true,
                dragEnable: true,
                center: pp,//传入地址的经纬度
                zoom: 13
            });

            mapInstance.on('complete', function () {
                AMap.plugin(['AMap.Geocoder', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.LngLat', 'AMap.Pixel', 'AMap.Icon'], () => {
                    let markPoint = new AMap.Marker({
                        position: new AMap.LngLat(obj.longitude, obj.latitude),
                        offset: new AMap.Pixel(-10, -10),
                        icon: mark, // 添加 Icon 图标 URL
                        title: '上课地址',
                        label: {
                            // content: '<span style="color: darkgreen; font-size: x-large"><strong>上课地点</strong></span>'
                        }
                    });

                    let geocoder = new AMap.Geocoder({
                        city: "", //城市设为北京，默认：“全国”
                        radius: 1000 //范围，默认：500
                    });

                    let address = ''; // 点击坐标的详细地址；

                    geocoder.getAddress([obj.longitude, obj.latitude], (status, result) => {
                        if (status === 'complete' && result.regeocode) {
                            address = result.regeocode.formattedAddress;

                            //实例化信息窗体
                            let title = '详细地址：',
                                content = [];
                            content.push(address);

                            //构建自定义信息窗体
                            let infoWindow = new AMap.InfoWindow({
                                position: new AMap.LngLat(obj.longitude, obj.latitude),
                                offset: new AMap.Pixel(24, -4),
                                autoMove: true,
                                isCustom: true, //使用自定义窗体
                                content: createInfoWindow(title, content.join("<br/>"), mapInstance),
                            });

                            infoWindow.open(mapInstance);

                            //鼠标点击marker弹出自定义的信息窗体
                            AMap.event.addListener(markPoint, 'click', function () {
                                infoWindow.open(mapInstance, markPoint.getPosition());
                            });
                        } else {
                            console.error('根据经纬度查询地址失败')
                        }
                    });

                    //添加标识物
                    mapInstance.add(markPoint);
                });
            });
        }


        // 查询简历列表信息
        GetListResume({ tutor_id: JSON.parse(sessionStorage.getItem('userInfo')).id }).then(res => {
            if (res.code === '000000') {
                setResumeSelectionObj({
                    resumeOptionList: res.responseData
                })
            }
        }).catch(err => {
            console.error(err);
        })
    }, [props.orderDetailsObject]);


    return (
        <div className="order-details">

            <div className="form-box">
                <div className="status-style">
                    订单状态:
                    <b>{orderDetailsObject.apply_status? orderDetailsObject.apply_status: orderDetailsObject.status}</b>
                </div>
                <div className="form-tit">
                    <i className="mini-block" />
                    <strong>基本信息</strong>
                </div>
                <div className="form-con">
                    <List>
                        <List.Item>订单编号
                            <List.Item.Brief>{orderDetailsObject.code}</List.Item.Brief>
                        </List.Item>
                        <List.Item>发布时间
                            <List.Item.Brief>{orderDetailsObject.audit_time}</List.Item.Brief>
                        </List.Item>
                        <List.Item>家长姓名
                            <List.Item.Brief>{orderDetailsObject.parent_name}</List.Item.Brief>
                        </List.Item>
                        <List.Item>家长性别
                            <List.Item.Brief>{orderDetailsObject.parent_gender}</List.Item.Brief>
                        </List.Item>
                        <List.Item
                            multipleLine
                            platform="android"
                        >
                            辅导科目<List.Item.Brief> {orderDetailsObject.subjects} </List.Item.Brief>
                        </List.Item>
                        <List.Item>课时费<List.Item.Brief>{orderDetailsObject.class_fee ? "￥" + orderDetailsObject.class_fee / 100 : ''} </List.Item.Brief></List.Item>
                        <List.Item>
                            中介费<List.Item.Brief> {orderDetailsObject.brokerage_fee ? "￥" + orderDetailsObject.brokerage_fee / 100 : ''} </List.Item.Brief>
                        </List.Item>
                        <List.Item>试讲地址
                            <List.Item.Brief> {orderDetailsObject.trial_address} </List.Item.Brief>
                        </List.Item>
                    </List>
                </div>

                <div className="form-tit">
                    <i className="mini-block" />
                    <strong>
                        可授课时间段
                            </strong>
                </div>
                <div className="form-con">
                    <Accordion defaultActiveKey="0" className="my-accordion">
                        {
                            JSON.parse(orderDetailsObject.learn_hours).map((item, index) => {
                                return <Accordion.Panel header={item.week} key={index}>
                                    <List className="my-list">
                                        <List.Item extra={item.startTime}>开始日期</List.Item>
                                        <List.Item extra={item.endTime}>结束日期</List.Item>
                                    </List>
                                </Accordion.Panel>
                            })
                        }
                    </Accordion>
                </div>

                <div className="form-tit">
                    <i className="mini-block" />
                    <strong>
                        上课地址
                    </strong>
                </div>
                <div className="form-con">
                    <List>
                        <List.Item
                            multipleLine
                            platform="android"
                        >
                            地址<List.Item.Brief> {orderDetailsObject.learn_address} </List.Item.Brief>
                        </List.Item>
                    </List>
                    <div id="amap"
                        style={orderDetailsObject.longitude !== null ? { width: '100%', height: '300px' } : {}}
                    />
                </div>
                <Accordion defaultActiveKey="0" className="my-accordion">
                    {
                        orderDetailsObject.students.map((item, index) => {
                            return (
                                <Accordion.Panel header={<b>{`辅导对象信息 ${index + 1}`}</b>} key={index}>
                                    <List>
                                        <List.Item extra={item.name}>性名</List.Item>
                                        <List.Item extra={item.gender}>性别</List.Item>
                                        <List.Item extra={item.grade}>年级</List.Item>
                                        <List.Item
                                            multipleLine
                                            platform="android"
                                        >
                                            辅导对象说明<List.Item.Brief> {item.note} </List.Item.Brief>
                                        </List.Item>
                                    </List>
                                </Accordion.Panel>

                            )
                        })
                    }
                </Accordion>
                <div className="form-tit">
                    <i className="mini-block" />
                    <strong>其他信息</strong>
                </div>
                <div className="form-con">
                    <List>
                        <List.Item
                            multipleLine
                            platform="android"
                        >
                            工作要求<List.Item.Brief> {orderDetailsObject.demand} </List.Item.Brief>
                        </List.Item>
                    </List>
                </div>
                {
                    btnFn()
                }

            </div>

            {/* 选择简历 */}
            <Modal
                popup
                visible={resumeSelectionObj.resumeSelectionVisible}
                onClose={() => {
                    setResumeSelectionObj({
                        resumeSelectionVisible: false,
                        resumeOptionList: resumeSelectionObj.resumeOptionList
                    })
                }}
                animationType="slide-up"
            >
                <List renderHeader={() => <div>简历列表</div>} className="popup-list">
                    {(resumeSelectionObj.resumeOptionList).map((i, index) => (
                        <Radio.RadioItem key={index} onChange={() => {
                            setResumeSelectionObj({
                                resumeOptionList: resumeSelectionObj.resumeOptionList,
                                resumeSelection: i.id,
                                resumeSelectionVisible: true,
                            })
                        }}
                        >
                            {`${(index + 1)}.${i.resume_code}`}
                            <List.Item.Brief>说明：{i.note}</List.Item.Brief>
                            <List.Item.Brief>更新时间：{i.update_time}</List.Item.Brief>
                        </Radio.RadioItem>
                    ))}
                    <List.Item>
                        <Button type="primary" onClick={() => {
                            setResumeSelectionObj({
                                resumeSelectionVisible: false,
                                resumeOptionList: resumeSelectionObj.resumeOptionList,
                                resumeSelection: resumeSelectionObj.resumeSelection
                            })

                            Modal.alert('提示', '确认选择此份简历报名 ?', [
                                { text: '取消', onPress: () => console.log('cancel') },
                                { text: '确定', onPress: () => handleSubmit() },
                            ])
                        }}
                        >选中</Button>
                    </List.Item>
                </List>
            </Modal>

            {/* 退款说明 */}
            <Modal
                popup
                visible={refundDetailsVisible}
                maskClosable
                title={<h4><strong>申请退款</strong></h4>}
                onCLose={hideRefund}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: hideRefund
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '确定', onPress: handleRefund
                }]}
                animationType="slide-up"
            >
                <List>
                    <TextareaItem
                        placeholder="退款说明"
                        rows={7}
                        onChange={setComment}
                    />
                </List>
            </Modal>

            {/* 试讲开始 */}
            <Modal
                popup
                visible={trialVisible}
                maskClosable
                title={<h4><strong>更新试讲信息</strong></h4>}
                animationType="slide-up"
                onClose={hideTrial}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: hideTrial
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '确定', onPress: handleTrialStart
                }]}
            >

                <List>
                    <TextareaItem
                        placeholder="试讲地址"
                        rows={7}
                        clear
                        count={200}
                        onChange={setAddress}
                    />
                </List>

            </Modal>

            <Modal
                popup
                visible={trialSuccessVisible}
                maskClosable
                title={<h4><strong>试讲成功</strong></h4>}
                animationType="slide-up"
                onClose={hideTrialSuccess}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: hideTrialSuccess
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '确定', onPress: handleTrialSuccess
                }]}
            >

                <List>
                    <TextareaItem
                        placeholder="试讲成功的说明"
                        rows={7}
                        clear
                        count={200}
                        onChange={setSuccessComment}
                    />
                </List>

            </Modal>

            <Modal
                popup
                visible={trialFailVisible}
                maskClosable
                title={<h4><strong>试讲失败</strong></h4>}
                animationType="slide-up"
                onClose={hideTrialFail}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: hideTrialFail
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '确定', onPress: handleTrialFail
                }]}
            >

                <List>
                    <TextareaItem
                        placeholder="试讲失败的说明"
                        rows={7}
                        clear
                        count={200}
                        onChange={setFailComment}
                    />
                </List>

            </Modal>

            {/* 协议 */}
            <Modal
                popup
                visible={showProtocol}
                title={<h3>用户协议</h3>}
                maskClosable
                onCLose={hideP}
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: hideP
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '同意并继续', onPress: () => {
                        sessionStorage.setItem("fee", orderDetailsObject.brokerage_fee);
                        sessionStorage.setItem("pay_order_id", orderDetailsObject.id);
                        props.history.push({
                            pathname: '/payOfOrder',
                            data: orderDetailsObject
                        })
                    }
                }]}
                animationType="slide-up"
            >
                <div dangerouslySetInnerHTML={{ __html: protocol }}></div>
            </Modal>
        </div>
    )
};

export default withRouter(PreOrderDetails);